# !/usr/bin/env python
# coding=utf-8
# @Time    : 2018/5/31 8:46
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/scrayp_test1.git
# @File    : my_decorator.py
# @Software: PyCharm
# @Version: 2.7.5
from functools import wraps
from py3_utils import my_time, my_return
from ins_provider import paic_data
import time


def desc_time(s):
	def wrapper(func):
		name = func.__name__  # 给变量name赋值 确定访问的函数
		func_identify = {name: 0, 'second': s}

		@wraps(func)
		def inner(*args, **kwargs):
			use_time = func_identify[name] + func_identify['second']  # 需等待这些时间之后才可以再次访问

			now_time = time.time()
			re_time = use_time - now_time  # 这个结果是一个负数
			if now_time > use_time:  # 如果当前时间大于等待的时间
				res = func(*args, **kwargs)
				func_identify[name] = now_time  # 给 func_identify[name] 重新赋值
			else:
				# print("请在{}秒之后访问".format(round(re_time)))
				res = "请在{}秒之后访问".format(round(re_time))
				res = my_return.my_return.get_fail("请求频率过快，"+res).to_string()
			return res

		return inner

	return wrapper


def print_execute_time():
	def decorator(f):
		@wraps(f)
		def decorated_function(*args, **kwargs):
			t1 = my_time.get_timestamp()
			try:
				return f()
			finally:
				t2 = my_time.get_timestamp() - t1
				print('excute:' + f.__name__ + ' pass:' + str(t2))

		return decorated_function

	return decorator


def handle_exception():
	def decorator(f):
		@wraps(f)
		def decorated_function(*args, **kwargs):
			try:
				return f(*args, **kwargs)
			except Exception as e:
				print('exception:' + f.__name__ + ' error:' + repr(e))

		return decorated_function

	return decorator


def check_login():
	def decorator(f):
		@wraps(f)
		def decorated_function(*args, **kwargs):
			try:
				if not paic_data.login_status():
					return my_return.my_return.get_fail('您还没有登录报价工具').to_string()
				return f(*args, **kwargs)
			except Exception as e:
				print('exception:' + f.__name__ + ' error:' + repr(e))

		return decorated_function

	return decorator


def check_permission(target_api):
	def decorator(f):
		@wraps(f)
		def decorated_function(*args, **kwargs):
			try:
				if target_api not in paic_data.get_permission() or not paic_data.get_permission().get(target_api):
					return my_return.my_return.get_fail('没有此权限').to_string()
				return f(*args, **kwargs)
			except Exception as e:
				print('exception:' + f.__name__ + ' error:' + repr(e))

		return decorated_function

	return decorator



@print_execute_time()
def aaa():
	import time
	time.sleep(1)
	print(123)


@desc_time(10)  # 在这儿参数为设置调用间隔时间
def foo1(*args, **kwargs):
	print('执行foo1--执行成功!')
	return 'result'


if __name__ == '__main__':
	# 测试代码
	for i in range(50):
		time.sleep(1)
		print(foo1())
